package com.sky.service.impl;

import com.sky.constant.DefaultConstant;
import com.sky.context.BaseContext;
import com.sky.dto.AddressBookAddDTO;
import com.sky.dto.AddressBookSetDefaultDTO;
import com.sky.dto.AddressBookUpdateDTO;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class AddressBookServiceImpl implements AddressBookService {


    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> list() {
        // 获取当前用户id
        Long userId = BaseContext.getCurrentId();
        // 查数据库
        return addressBookMapper.selectByUserId(userId);
    }

    @Override
    public void add(AddressBookAddDTO dto) {
        // 直接insert到数据库
        AddressBook addressBook = new AddressBook();
        BeanUtils.copyProperties(dto, addressBook);
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBook.setIsDefault(DefaultConstant.NO);
        addressBookMapper.insert(addressBook);
    }

    @Override
    public AddressBook getById(Long id) {
        return addressBookMapper.selectById(id);
    }

    @Override
    public void update(AddressBookUpdateDTO dto) {
        // 处理默认，当前的修改如果是改成默认，需要保证不能出现2个默认
        Integer isDefault = dto.getIsDefault();
        // 如果是把当前记录修改成默认
        if(isDefault != null && Objects.equals(isDefault, DefaultConstant.YES)){
            // 把之前的默认给取消掉
            addressBookMapper.updateNotDefaultByUserId(BaseContext.getCurrentId());
            // 设置当前的为默认
            AddressBook addressBook = new AddressBook();
            BeanUtils.copyProperties(dto, addressBook);
            addressBook.setUserId(BaseContext.getCurrentId());
            addressBookMapper.update(addressBook);
        }else{
            // 根据id更新
            AddressBook addressBook = new AddressBook();
            BeanUtils.copyProperties(dto, addressBook);
            addressBook.setUserId(BaseContext.getCurrentId());
            addressBookMapper.update(addressBook);
        }
    }

    @Override
    public void setDefault(AddressBookSetDefaultDTO dto) {
        // 把之前的默认给取消掉
        addressBookMapper.updateNotDefaultByUserId(BaseContext.getCurrentId());
        // 设置当前的为默认
        AddressBook addressBook = new AddressBook();
        addressBook.setIsDefault(DefaultConstant.YES);
        addressBook.setId(dto.getId());
        addressBookMapper.update(addressBook);
    }

    @Override
    public void delete(Long id) {
        addressBookMapper.deleteById(id);
    }
}
